package com.netease.ticket;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.NameValuePair;
public class Util {
	/**
	 * @param args
	 */
	
	//private static String jsonFile = "passengerInfo.json";
	
	public static void setReqHeader(HttpMethod method, String refer, String cookie)
	{
		
		method.setRequestHeader("Host", "dynamic.12306.cn");
		//method.setRequestHeader("DNT", "1"); 
		method.setRequestHeader("origin", "http://dynamic.12306.cn");
    	method.setRequestHeader("Connection", "keep-alive");
    	method.setRequestHeader("Cache-Control", "no-cache");
    	method.setRequestHeader("Accept", "text/html, application/xhtml+xml, */*");
    	method.setRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
    	method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	if(refer != null && !refer.isEmpty())method.setRequestHeader("Referer", refer);

    	method.setRequestHeader("Accept-Language", "zh-CN");
    	if(cookie != null && !cookie.isEmpty())method.setRequestHeader("Cookie", cookie);
	}
	
	public static int redirect(HttpMethod method, HttpClient client, String refer, String cookie) throws Exception
	{
		Header location = null;
		location = method.getResponseHeader("location");
		int code = 0;

	   	System.out.println(location.getValue());
	   	if(location != null){
		    String newUrl = location.getValue();
		    	 
	    	if(newUrl == null || newUrl.equals(""))newUrl = "/";
	    	else
	    	{
	    		method = new GetMethod(newUrl);
	    		setReqHeader(method, refer, cookie);
		    	code = client.executeMethod(method);
		    	System.out.println("Redirect to: " + newUrl + ",result:" + method.getStatusLine().toString());
		    	 
		    	System.out.println(method.getResponseBodyAsString());
	    	}
	   	}
	   	
	   	return code;
	}
	
	public static String paseToken(String html, int startIndex)
	{
		 int len = 0;
		 String tmp  = html.substring(startIndex);
		 String value = "value=\"";
		 startIndex += tmp.indexOf(value) + value.length();
		 for(; len < 200;len++)
		 {
			 if((html.charAt(startIndex + len) >= '0' && html.charAt(startIndex + len) <= '9')
					 || (html.charAt(startIndex + len) >= 'a' && html.charAt(startIndex + len) <= 'z')
					 || (html.charAt(startIndex + len) >= 'A' && html.charAt(startIndex + len) <= 'Z'))
			 {
				 continue;
			 }
			 else
			 {
				 return html.substring(startIndex, startIndex + len);
			 }
		 }
		 return "";
	}
	
	public static String cookie2String(Cookie[] cookies)
	{
		String cookie = "";
		if(cookies != null){
			for(int i=0; i< cookies.length; i++)
			{
		   		cookie += cookies[i].getName() + "=" + cookies[i].getValue();
		   		if(i < cookies.length-1) cookie +="; ";
			}
		}
		return cookie;
	}
	
	/**
	 * 对验证码进行进一步处理
	 * @return
	 */
	public static String paseYzm(String yzm)
	{
		String ret = "";
		for(int i= 0; i< yzm.length(); i++)
		{
			
			if(yzm.charAt(i) >= 'A' && yzm.charAt(i) <= 'Z'
				|| yzm.charAt(i) >= '0' && yzm.charAt(i) <= '9')
			{
				ret += yzm.charAt(i);
			}
		}
		
		return ret;
	}
	/*
	public static PassengerInfo object2json(Object o, String fileName)
	{
		PassengerInfo pi = new PassengerInfo();
		JSONObject json = JSONObject.fromObject(o);
		
		return pi;
	}
	
	public static void PassengerInfoToJSON(ArrayList<PassengerInfo> list) throws Exception{
		if(list == null) return;
        JSONArray jsonArray = JSONArray.fromObject( list );  
        System.out.println( jsonArray );
        File storeFile = new File(jsonFile);
	    FileOutputStream output = new FileOutputStream(storeFile);
	     
	     //得到网络资源的字节数组,并写入文件 
	    output.write(String.valueOf(jsonArray).getBytes());
	    output.close();
        // prints ["first","second"]  
    }*/
	
	public static NameValuePair getJsResult(String fileName, String html)throws Exception{
		NameValuePair jsResult;
	   
	    html = html.substring("(function ($){var jq=$.ajax;".length(), html.length() - ")(jQuery);".length() - 1);
	    
	    //得到网络资源的字节数组,并写入文件 
	    writeFile(fileName, html);
	    
	    //解析该JS文件
    	jsResult = JavaScriptExecutor.analyzeJS(fileName);
    	
    	return jsResult;
	}
	
	public static void writeFile(String fileName, String content)throws Exception
	{
		File storeFile = new File(fileName);
	    FileOutputStream output = new FileOutputStream(storeFile);
	    output.write(content.getBytes());
	    output.close();
	}
	
	public static String readFile(String fileName, String charSet) throws Exception
	{
		File file = new File(fileName);
        
		
        BufferedReader reader;
        String content = "";
          
        if(file.exists())
        {
        	content = "";
        	InputStreamReader read = new InputStreamReader (new FileInputStream(file),charSet);
	        reader =new BufferedReader(read);
	        String tempString = null;
	        
	        // 一次读入一行，直到读入null为文件结束
	        while ((tempString = reader.readLine()) != null) {
	        	content += tempString;
	        }
	           
	        reader.close();
        }
        
        return content;
	}
	
	/**
	 * 解析简单的json字串，如提交订单返回的{"checkHuimd":"Y", "check608":"Y", "msg":"", "errMsg":"Y"}
	 * @param json
	 * @return 结果集
	 */
	public static HashMap<String, String> paseSimpleJSON(String json)
	{
		json = json.replace("{", "");
		json = json.replace("}", "");
		json = json.replace("\r", "");
		json = json.replace("\n", "");
		json = json.replace("\t", "");
		String pairs[] = json.split(",");
		HashMap<String, String> ret = new HashMap<String, String>();
		for(int i = 0; i< pairs.length; i++)
		{
			pairs[i] = pairs[i].replace('\"', ' ');
			String keyValue[] = pairs[i].split(":");
			
			if(keyValue.length != 2) break;
			
			ret.put(keyValue[0].trim(), keyValue[1].trim());
		}
		
		return ret;
	}
	
	public static String str2seatType(String seat)
	{
		if(seat.equals("硬座") || seat.equals("yingzuo")) return "1";
		if(seat.equals("二等座") || seat.equals("2dengzuo") || seat.equals("erdengzuo")) return "O";
		if(seat.equals("硬卧") || seat.equals("yingwo")) return "3";
		if(seat.equals("一等座") || seat.equals("1dengzuo") || seat.equals("yidengzuo")) return "M";
		if(seat.equals("软卧") || seat.equals("ruanwo")) return "4";
		if(seat.equals("特等座") || seat.equals("tedengzuo")) return "P";
		if(seat.equals("商务座") || seat.equals("商务舱") || seat.equals("shangwuzuo") || seat.equals("shangwucang")) return "9";
		
		//默认硬座
		return "1";
	}
	
	public static PassengerInfo pasePassengerFile(String line) throws Exception
	{
		HashMap<String, String> map = paseSimpleJSON(line);
		PassengerInfo pi = new PassengerInfo();
		if(map.containsKey("passenger_seat"))
		{
			
			pi.seat = str2seatType(map.get("passenger_seat"));
			pi.ticket = map.get("passenger_ticket");
			pi.name = map.get("passenger_name");
			pi.cardno = map.get("passenger_cardno");
			pi.cardtype = map.get("passenger_cardtype");
			pi.mobileno = map.get("passenger_mobileno");
		}
		return pi;
	}
	
}
